var createError = require("http-errors");
var express = require("express");
const cors = require('cors');
const fs = require("fs");
var path = require("path");
var cookieParser = require("cookie-parser");
//var logger = require('morgan');

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var logRouter = require("./routes/log");
var app = express();
app.use(cors());
// view engine setup
app.set("views", path.join(__dirname, "views"));
//app.set('view engine', 'jade');
app.set("view engine", "pug");
//app.use(logger('dev'));
const logger = require("./utils/logger");
// 写入所有日志
app.use(logger.accessLog);
// 写入错误日志
app.use(logger.accessLogErr);
// 打印日志
app.use(logger.logger("dev"));

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/log", logRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  console.log('res:', res.message,err)

  // render the error page
  res.status(err.status || 500);
//res.render("error");
});
app.all("/", (req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET, POST");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "X-Requested-With,content-type, Authorization"
  );
  next();
});

module.exports = app;
//git clone https://gitee.com/ieduadmin_admin/express-api.git
//cd express-api
//git pull origin master
//docker build -t expressapi .
//docker run -d -p 4004:3000 -e MYSQL_HOST=121.40.63.234 -e MYSQL_PORT=3306 -e MYSQL_USER=root -e MYSQL_PASSWORD=Fycm2024 -e MYSQL_DATABASE=ecodedata_test  expressapi
//docker run -d -p 4004:3000 -e MYSQL_HOST=119.45.240.39 -e MYSQL_PORT=3306 -e MYSQL_USER=ztData -e MYSQL_PASSWORD=bPXREBwmFcMLA3sG -e MYSQL_DATABASE=ztdata  expressapi
//chmod +x update_and_restart.sh
//./update_and_restart.sh
